from django.shortcuts import render
from django.http import JsonResponse
from common.models import Customer,Room,RoomLog,waterbill
import datetime
from django.db.models import Q
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'hotelsys.settings'
from django.core import signing
from django.http import JsonResponse
from django.contrib.auth import authenticate,login
import datetime
import time
import json
#酒店房间的房间号列表
rid_list=['301','302','303','304','305']

# 生成报表
def createreport(request):    # token...
    token = request.META.get("HTTP_AUTHORIZATION")
    # 管理员的token是username|*****
    # 分隔符...
    strlist = token.split('|')
    src = signing.loads(strlist[1])
    if strlist[0] == src['username']:
        # 合法
        # 要求可以查看任意时间各个房间的报表
        # 获取时间戳
        request.params = json.loads(request.body)
        timestamp = request.params['time']
        timestamp = int(timestamp) / 1000
        timestamp = datetime.datetime.fromtimestamp(timestamp)  # 转化为datetime格式

        if timestamp:
            # 获取离该时间戳最近的各房间状态
            # 获取房间号列表
            roomlist = list(Room.objects.values_list('rid', flat=True))
            # print(roomlist)
            roominfolist = []
            for roomid in roomlist:
                roomlog = list(RoomLog.objects.filter(rid=roomid))
                if len(roomlog) > 0:
                    roominfolist.append(roomlog[-1])
                else:
                    roominfolist.append(-1)

            datalist = []
            len1 = len(roomlist)
            for i in range(len1):
                roomdist = {}
                roomdist['rid'] = roomlist[i]
                if roominfolist[i] != -1:
                    roomdist['state'] = roominfolist[i].onoff
                    roomdist['temp'] = roominfolist[i].temp
                    roomdist['mode'] = roominfolist[i].mode
                    roomdist['discount'] = roominfolist[i].discount
                else:
                    roomdist['state'] = 0
                    roomdist['temp'] = None
                    roomdist['mode'] = None
                    roomdist['discount'] = None
                datalist.append(roomdist)
            print(datalist)

            return JsonResponse({
                "error_code": 0,
                "data": datalist
            })

        return JsonResponse({'error_code': 1,
                             'msg': '请给出时间戳...'})
    else:
        # 不合法
        return JsonResponse({'error_code': 1,
                             'msg': '非法访问...'})

# 修改房间的优惠折扣
def discount(request):
    # token...
    token = request.META.get("HTTP_AUTHORIZATION")
    # 管理员的token是username|*****
    # 分隔符...
    print("dfsdfs")
    strlist = token.split('|')
    print(token)
    src = signing.loads(strlist[1])
    if strlist[0] == src['username']:
        # 获取房间号
        request.params = json.loads(request.body)
        roomrid = request.params['rid']
        # 获取优惠折扣
        roomdis = request.params['discount']

        if roomrid and roomdis:
            try:
                room = Room.objects.get(rid=roomrid)
            except Room.DoesNotExist:
                return JsonResponse({
                    'error_code': 1,
                    'msg': f'房间{roomrid}不存在'
                })

            if float(roomdis)<=1 and float(roomdis)>=0:
                room.discount = float(roomdis)
            else:
                return JsonResponse({'error_code': 1,
                                     'msg': 'discount不合法...'})

            # 生成日志
            log = RoomLog.objects.create(optime = datetime.datetime.now(),
                                         temp = room.temp,
                                         mode = room.mode,
                                         onoff = room.onoff,
                                         discount = room.discount,
                                         rid = room)

            # 保存到数据库
            room.save()

            return JsonResponse({'error_code': 0})

        if roomrid:
            return JsonResponse({'error_code': 1,
                                 'msg': '请给出优惠折扣...'})
        if roomdis:
            return JsonResponse({'error_code': 1,
                                 'msg': '请给出房间号...'})

        return JsonResponse({'error_code': 1,
                             'msg': '请给出房间号和优惠折扣...'})
    else:
        # 不合法
        return JsonResponse({'error_code': 1,
                             'msg': '非法访问...'})

# 管理员统一打开/关闭所有空调
def centeronoff(request):
    # token...
    token = request.META.get("HTTP_AUTHORIZATION")
    # 管理员的token是username|*****
    # 分隔符...
    strlist = token.split('|')
    src = signing.loads(strlist[1])
    strlist[0] = strlist[0].encode("latin1").decode("utf-8")
    print("******")
    if strlist[0] == src['username']:
        print("access...")
        # 获取state
        request.params = json.loads(request.body)
        state = request.params['state']
        # 获取房间号列表
        roomlist = list(Room.objects.values_list('rid', flat=True))
        # print(roomlist)
        for roomrid in roomlist:
            room = Room.objects.get(rid=roomrid)
            room.onoff = state
            if state == 1:
                # 打开空调需要初始化temp,mode,discount
                room.temp = 26
                room.mode = 'M'
            else:
                print("######")
                # 关闭空调需要将temp,mode,discount置空
                room.temp = None
                room.mode = None
            # 生成日志
            log = RoomLog.objects.create(optime=datetime.datetime.now(),
                                         temp=room.temp,
                                         mode=room.mode,
                                         onoff=room.onoff,
                                         discount=room.discount,
                                         rid=room)
            room.save()

        return JsonResponse({'error_code': 0})
    else:
        # 不合法
        return JsonResponse({'error_code': 1,
                             'msg': '非法访问...'})


#管理员登录
def admin_login(request):
    request.params = json.loads(request.body)
    userName = request.params['username']
    passWord = request.params['password']
    user = authenticate(username = userName,password = passWord)
    if user is not None:
        if user.is_active:
            if user.is_superuser:
                login(request,user)
                token = str(userName)+'|'+str(signing.dumps({'username':userName}))
                data = {'error_code':0,'data':{'uid':user.id,'username':userName,'token':token}}
                return JsonResponse(data)
            else:
                return JsonResponse({'error_code': 1, 'data': "请使用管理员账户登录"})

        else:
            return JsonResponse({'error_code':1,'data':"账户已被禁用"})
    else:
        return JsonResponse({'error_code':1,'data':"账户名或者密码错误"})

#管理员查看流水，使用表格waterbill
def createwaterbills(request):
    token = request.META.get("HTTP_AUTHORIZATION")
    # 管理员的token是username|*****
    # 分隔符...
    strlist = token.split('|')
    src = signing.loads(strlist[1])
    strlist[0] = strlist[0].encode("latin1").decode("utf-8")
    if strlist[0] == src['username']:
        roomdata = []
        request.params = json.loads(request.body)
        timestamp_raw = request.params['date'] #时间戳格式(ms为单位)

        if timestamp_raw:
            timestamp = int(timestamp_raw) / 1000 #(s为单位)
            d = datetime.datetime.fromtimestamp(timestamp) #转化为datetime格式
            request_time = d.date()   #提取日期
            for room in rid_list:
                op_list = waterbill.objects.filter(rid_id=room).values()  #所有这个房间的操作列表

                account = None
                timestamp = None
                for op in op_list:
                    if op["time"].date() == request_time:
                        account = op["money"]
                        time = Room.objects.filter(rid=room).values("lastCheckoutDate")
                        # time = datetime.datetime.strptime(time, "%Y-%m-%d %H:%M:%S").replace(tzinfo=datetime.timezone.utc).timestamp()
                        if time:
                            timestamp = time[0]["lastCheckoutDate"].strftime('%Y-%m-%d %H:%M:%S')
                            timestamp = int(datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S").replace(
                                tzinfo=datetime.timezone.utc).timestamp()*1000)

                roomdata.append({'rid': room, 'time':timestamp, 'account': account})
            return JsonResponse({'error_code': 0, 'data':roomdata})
        else:
            return JsonResponse({'error_code': 1, 'data': '非法操作'})
    else:
        return JsonResponse({'error_code': 1, 'data': '未登录','redict':'/admin/login'})


